import pandas as pd
from flask import (Flask, render_template, request, jsonify, flash,
                   redirect, url_for, session, send_from_directory)
import sys
import datetime
import json
import os
import ast
app = Flask(__name__)
app.secret_key = "dfaskljdkf4378943%&*%7"


@app.route('/')
def start_web():
    if session.get('admin', None) is None:
        return redirect(url_for("login"))
    json_path = "index_data.json"
    profit = {}
    if os.path.exists(json_path):
        with open(json_path) as fp:
            profit = json.load(fp)
    return render_template('index.html', profit=profit)


@app.route('/indexData')
def index_data():
    json_path = "index_data.json"
    if os.path.exists(json_path):
        with open(json_path) as fp:
            profit = json.load(fp)
    result = dict()
    result["profit"] = profit
    result = json.dumps(result)
    return result


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('pwd')
        permission_df = pd.read_csv('permissions.csv')
        filter_df = permission_df[permission_df['username'] == username]
        if filter_df.empty:
            flash("用户名或密码错误")
        else:
            if password != str(filter_df.iloc[0]['password']):
                flash("用户名或密码错误")
            else:
                session['admin'] = username
                session['permissions'] = ast.literal_eval(filter_df.iloc[0]['permissions'])
                return redirect(url_for("start_web"))
    return render_template('login.html')

@app.route('/loginOut')
def login_out():
    session.pop('admin')
    return redirect(url_for('login'))


@app.route('/permissionManage')
def permission_manage():
    if session.get('admin', None) is None:
        return redirect(url_for("login"))
    path = request.path.split('/')[1]
    if path not in session['permissions']:
        return redirect(url_for("no_permission"))
    return render_template('permissionManage.html', version=str(datetime.datetime.today()))


@app.route('/noPermission')
def no_permission():
    return render_template('noPermission.html')


@app.route('/permissionManageData')
def permission_manage_data():
    df = pd.read_csv('permissions.csv')
    result_list = []
    for index, row in df.iterrows():
        each_dict = dict()
        each_dict["user_name"] = row["username"]
        each_dict["password"] = row["password"]
        permissions = ast.literal_eval(row["permissions"])
        permissions_status = ["1"]*len(permissions)
        each_dict["permissions"] = ",".join(permissions)
        each_dict["permissions_status"] = ",".join(permissions_status)

        each_dict["newest_visit_time"] = str(datetime.datetime.now())
        result_list.append(each_dict)
    result = dict()
    result["resultList"] = result_list
    result = json.dumps(result)
    return result


@app.route('/simulateTrade')
def simulate_trade():
    if session.get('admin', None) is None:
        return redirect(url_for("login"))
    path = request.path.split('/')[1]
    if path not in session['permissions']:
        return redirect(url_for("no_permission"))
    return render_template('simulateTrade.html', version=str(datetime.datetime.today()))


@app.route('/alertInfo')
def alert_info():
    df = pd.DataFrame([
        {
        "user_name": "zhanghang",
        "profit" : 20},
        {
            "user_name": "suli",
            "profit": 15},
        {
            "user_name": "dalong",
            "profit": 8},
    ])
    alert_info_list = []
    if df is None:
        alert_info_list.append("没有客户收益超过8%")
    else:
        for index, row in df.iterrows():
            user_name = row['user_name']
            profit = row['profit']
            if profit >= 10:
                alert_info_list.append("客户 "+user_name+" 收益达到10%,请尽快结算!!!")
            else:
                alert_info_list.append("客户 "+user_name+" 收益达到8%，请注意!!!")
    result = dict()
    result['alertInfo'] = alert_info_list
    result = json.dumps(result)
    return result

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    app.run(threaded=True, host='0.0.0.0', port=8006)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
